﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using Repository.Dtos;
using Repository.Service;
using System.Diagnostics.CodeAnalysis;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace Controller.Controllers
{
    public class UserController : ControllerBase {
		private readonly SurveyService _surveyService;
		private readonly ConfigurationManager configuration;
		public UserController(SurveyService surveyService, ConfigurationManager configuration) {
			_surveyService = surveyService;
			this.configuration = configuration;
		}

		/// <summary>
		/// 添加新用户
		/// </summary>
		[HttpPost("Register")]
		public async Task<ActionResult<string>> AddNewUser([FromBody] UserCredentialsDto userInfo) {
			if (await _surveyService.AddUser(userInfo)) {
				return "Add Success";
			}
			return $"Add Failed : User Exist";
		}

		/// <summary>
		/// 登录
		/// </summary>
		/// <example>
		/// Username : dl
		/// Password : 111
		/// </example>
		[HttpPost("login")]
		public ActionResult Login([FromBody] UserCredentialsDto info) {
			var username = info.UserName;
			var password = info.Password;
			var res = _surveyService.GetUserByName(username);
			var usr = res?.Result;

			if (usr == null) {
				return BadRequest("用户不存在");
			}
			try {
				// 验证用户名和密码是否正确
				if (usr.Password.Equals(password)) {
					return Ok(new { access_token = CreateToken(), userId = usr.Id });
				}
			}
			catch (Exception ex) {
				Console.WriteLine($"{ex.Message}");
				return BadRequest(ex.Message);
			}
			return BadRequest("用户名或密码错误");
		}


		//[HttpGet("TestJWT")]
		//[Authorize]
		//public ActionResult<string> Test() {
		//	return "ok";
		//}

		private string CreateToken() {
			// 1. 定义需要使用到的Claims
			var claims = new[]
			{
				new Claim("Id", "999"),
				new Claim("Name", "Admin")
			};

			// 2. 从 appsettings.json 中读取SecretKey
			var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JWT:SecretKey"]));

			// 3. 选择加密算法
			var algorithm = SecurityAlgorithms.HmacSha256;

			// 4. 生成Credentials
			var signingCredentials = new SigningCredentials(secretKey, algorithm);

			// 5. 从 appsettings.json 中读取Expires
			var expires = Convert.ToDouble(configuration["JWT:Expires"]);

			// 6. 根据以上，生成token
			var token = new JwtSecurityToken(
				configuration["JWT:Issuer"],     //Issuer
				configuration["JWT:Audience"],   //Audience
				claims,                          //Claims,
				DateTime.Now,                    //notBefore
				DateTime.Now.AddDays(expires),   //expires
				signingCredentials               //Credentials
			);

			// 7. 将token变为string
			var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);

			return jwtToken;
		}
	}
}
